package com.shenganyuan.smac.work;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.oklib.base.CoreBaseFragment;
import com.oklib.utils.Logger.Logger;
import com.oklib.utils.calculate.ArithUtil;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.utils.view.ToastUtils;
import com.oklib.widget.dialog.ConfirmDialog;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.change.ActChangeRecords;
import com.shenganyuan.smac.check.ActCheckInfoAdd;
import com.shenganyuan.smac.check.ActCheckRecords;
import com.shenganyuan.smac.checkin.ActCheckin;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.ApiMainUser;
import com.shenganyuan.smac.common.beans.ApiMainWork;
import com.shenganyuan.smac.common.beans.ApiRisk;
import com.shenganyuan.smac.common.beans.EventRefreshPage;
import com.shenganyuan.smac.common.beans.LocationInfo;
import com.shenganyuan.smac.common.beans.RiskPoint;
import com.shenganyuan.smac.common.beans.User;
import com.shenganyuan.smac.common.data.AnyPrefUtil;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.common.utils.DataConverter;
import com.shenganyuan.smac.common.view.CommonBottomListDialog;
import com.shenganyuan.smac.common.view.DialogWorkOperate;
import com.shenganyuan.smac.risk.ActRiskRecords;
import com.shenganyuan.smac.worklog.ActWorkLog;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author Damon
 * @date 2017/12/14
 */

public class FrgMainWork extends CoreBaseFragment implements AMapLocationListener, LocationSource, PopupMenu.OnMenuItemClickListener {
    @BindView(R.id.work_user_department)
    TextView workUserDepartment;
    @BindView(R.id.work_user_username)
    TextView workUserUsername;
    @BindView(R.id.work_toolbar)
    Toolbar workToolbar;
    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.work_check_frequence)
    TextView work_check_frequence;
    @BindView(R.id.floating_action_button)
    FloatingActionButton floatingActionButton;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private OnLocationChangedListener mListener;
    private AMap aMap;
    private RxPermissions permissions;
    private Map<String, Permission> allNeadPermissions;
    private ConfirmDialog confirmDialog;
    //地图中心点
    private LatLng centerPoint;
    private List<LatLng> pointList = new ArrayList<>();
    private Marker centerMarker;
    /**
     * 地图上除了本地位置的所有marker
     */
    private List<Marker> markers = new ArrayList<>();

    public static FrgMainWork newInstance() {
        Bundle args = new Bundle();
        FrgMainWork fragment = new FrgMainWork();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.main_frg_work;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mapView.onCreate(savedInstanceState);
        getPermission();
    }

    @Override
    public void initData() {
        super.initData();
        String txt = getContext().getResources().getStringArray(R.array.array_work_check_frquence)[0];
        work_check_frequence.setText(txt);
        User user = App.getCurrentUser();
        workUserUsername.setText(user.getName());
    }

    private String getFrequencyQueryStr() {
        String[] arra = getContext().getResources().getStringArray(R.array.array_work_check_frquence);
        String currentTxt = work_check_frequence.getText().toString();
        String string = null;
        int index = 0;
        for (int i = 0; i < arra.length; i++) {
            string = arra[i];
            if (string.equals(currentTxt)) {
                index = i;
            }
        }
        String result = "A";
        switch (index) {
            case 0:
                result = "A";
                break;
            case 1:
                result = "B";
                break;
            case 2:
                result = "C";
                break;
            case 3:
                result = "D";
                break;
            case 4:
                result = "E";
                break;
        }
        return result;
    }

    /**
     * 从服务器获取信息
     *
     * @param frequency
     */
    private void getMainData(String frequency) {
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class)
                .mainWork(user.getId(), frequency, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(new ApiCallbackSubscriber<ApiMainWork>(new ACallback<ApiMainWork>() {
                            @Override
                            public void onSuccess(ApiMainWork data) {
                                try {
                                    refreshView(data);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                SnackbarUtil.showShort(getView(), "获取主页信息失败");
                            }
                        })

                );
    }

    /**
     * 获取风险点信息
     *
     * @param frequency
     */
    private void getRisks(String frequency) {
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).mainRisks(user.getId(), frequency, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiRisk>() {
            @Override
            public void onSuccess(ApiRisk data) {
                try {
                    List<RiskPoint> gkzydyBeans = data.getGkzydy();
                    if (gkzydyBeans != null && gkzydyBeans.size() > 0) {
                        displayMarkers(gkzydyBeans);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getView(), "登录失败");
            }
        }));
    }

    private void refreshView(ApiMainWork apiMainWork) {
        if (apiMainWork == null) {
            return;
        }
        ApiMainUser djtxtdBean = apiMainWork.getDjtxtd();
        if (djtxtdBean != null) {
            App.setApiMainUser(djtxtdBean);
            String departmenName = djtxtdBean.getBumen();
            String userName = djtxtdBean.getName();
            workUserDepartment.setText(departmenName);
            workUserUsername.setText(userName);
        }
        List<RiskPoint> gkzydyBeans = apiMainWork.getGkzydy();
        if (gkzydyBeans != null && gkzydyBeans.size() > 0) {
            displayMarkers(gkzydyBeans);
        }
    }

    private void getPermission() {
        if (allNeadPermissions == null) {
            allNeadPermissions = new HashMap<>();
        }
        if (permissions == null) {
            permissions = new RxPermissions(getActivity());
        }
        permissions
                .requestEach(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    allNeadPermissions.put(permission.name, permission);
                    //全部权限请求完毕
                    if (allNeadPermissions.size() == 3) {
                        Permission externalPermission = allNeadPermissions.get(Manifest.permission.ACCESS_COARSE_LOCATION);
                        Permission readPhonePermission = allNeadPermissions.get(Manifest.permission.ACCESS_FINE_LOCATION);
                        Permission cameraPermission = allNeadPermissions.get(Manifest.permission.CAMERA);
                        if (externalPermission.granted && readPhonePermission.granted && cameraPermission.granted) {
                            init();
                        } else {
                            allNeadPermissions.clear();
                            Permission deniedPermission = null;
                            if (!externalPermission.granted) {
                                deniedPermission = externalPermission;
                            } else if (!readPhonePermission.granted) {
                                deniedPermission = readPhonePermission;
                            } else if (!cameraPermission.granted) {
                                deniedPermission = cameraPermission;
                            }
                            showConfirmDialog(deniedPermission);
                        }
                    }
                });
    }

    private void showConfirmDialog(Permission permission) {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(getContext());
            confirmDialog.setCanceledOnTouchOutside(false);
            confirmDialog.setCancelable(false);
            confirmDialog.setMessage("需要您开启权限我们才能为您服务");
            confirmDialog.setNevigateButton("取消", view -> {
                confirmDialog.dismiss();
                App.getInstance().exitApp();
            });
        }
        confirmDialog.setPositiveButton("确定", view -> {
            confirmDialog.dismiss();
            getPermission();
        });
        confirmDialog.show();
    }

    /**
     * 检查频率选择
     */
    private void popWorkFrequence(View view) {
        PopupMenu popupMenu = new PopupMenu(getContext(), view);
        popupMenu.setOnMenuItemClickListener(this);
        popupMenu.inflate(R.menu.menu_work_frequence);
        popupMenu.show();
    }

    /**
     * 底部操作
     *
     * @param view
     */
    private void bottomSheet(View view) {
        DialogWorkOperate dialogWorkOperate = DialogWorkOperate.netInstance();
        dialogWorkOperate.show(getFragmentManager(), DialogWorkOperate.class.getName());
        dialogWorkOperate.setOnWorkOperationClicked(new DialogWorkOperate.OnWorkOperationClicked() {
            @Override
            public void onOperationClicked(View view) {
                switch (view.getId()) {
//                    case R.id.btn_patrol_position:
//                        showToast("巡查位置");
//                        gotoWorkPage(ActPosition.class);
//                        break;
                    case R.id.btn_patrol_record:
                        gotoWorkPage(ActCheckRecords.class);
                        break;
                    case R.id.btn_hazard_record:
                        gotoWorkPage(ActRiskRecords.class);
                        break;
                    case R.id.btn_correct_record:
                        gotoWorkPage(ActChangeRecords.class);
                        break;
                    case R.id.btn_builder_record:
                        gotoWorkPage(ActWorkLog.class);
                        break;
                    case R.id.btn_sign_in:
                        gotoWorkPage(ActCheckin.class);
                        break;
                    case R.id.btn_scan:
                        openScan();
                        break;
                }
            }
        });
    }


    private void gotoWorkPage(Class cls) {
        Intent intent = new Intent(getContext(), cls);
        startActivity(intent);
    }

    private void gotoWorkPageWithBundle(Bundle bundle, Class cls) {
        Intent intent = new Intent(getContext(), cls);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public final static int REQUEST_CODE = 10000;

    private void openScan() {
        Intent intent = new Intent(_mActivity, CaptureActivity.class);
//        startActivityForResult(this,intent, REQUEST_CODE);
        _mActivity.startActivityFromFragment(this, intent, REQUEST_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (requestCode == REQUEST_CODE) {
                //处理扫描结果（在界面上显示）
                if (null != bundle) {
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String result = bundle.getString(CodeUtils.RESULT_STRING);
                        String id = "";
                        if (result != null && result.contains("id=")) {
                            String[] strings = result.split("id=");
                            id = strings[1];
                        }
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("pointId", id);
                        gotoWorkPageWithBundle(bundle1, ActCheckInfoAdd.class);
                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        showToast("解析失败");
                    }
                }
            }
        }
    }

    @OnClick({R.id.work_user_department, R.id.work_user_username, R.id.floating_action_button, R.id.work_check_frequence})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.work_user_department:
                break;
            case R.id.work_user_username:
                break;
            case R.id.floating_action_button:
                bottomSheet(view);
                break;
            case R.id.work_check_frequence:
                popWorkFrequence(view);
                break;
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        onFrequenceChosed(item);
        return false;
    }

    private void onFrequenceChosed(MenuItem item) {
        int position = 0;
        switch (item.getItemId()) {
            case R.id.work_menu_day:
                position = 0;
                break;
            case R.id.work_menu_week:
                position = 1;
                break;
            case R.id.work_menu_month:
                position = 2;
                break;
            case R.id.work_menu_quarter:
                position = 3;
                break;
            case R.id.work_menu_year:
                position = 4;
                break;
        }
        String txt = getContext().getResources().getStringArray(R.array.array_work_check_frquence)[position];
        showToast(txt);
        work_check_frequence.setText(txt);
        getRisks(getFrequencyQueryStr());
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        setUpMap();
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(50, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        ////设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。
        myLocationStyle.showMyLocation(false);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。

        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();
                } else {
                    marker.showInfoWindow();
                }
                if ("我的位置".equals(marker.getTitle())) {
                    return true;
                } else {
                    pickMaps(marker.getPosition());
                }
                return true;
            }
        });

    }

    /**
     * 选择地图
     */
    private void pickMaps(LatLng latLng) {
        if (latLng == null || latLng.longitude == 0 || latLng.latitude == 0) {
            ToastUtils.showToast(getContext(), "gps数据不合法");
            return;
        }
        ArrayList<String> datas = new ArrayList<>();
        datas.add("高德");
        datas.add("百度");
        CommonBottomListDialog commonBottomListDialog = CommonBottomListDialog.newInstance(datas);
        commonBottomListDialog.setTitle(getString(R.string.tilte_choose_map));
        commonBottomListDialog.setDefaultCheckValue("");
        commonBottomListDialog.addOnSingleCheckListener(new CommonBottomListDialog.OnSingleCheckListener() {
            @Override
            public void onSingleCheck(int position, String value) {
                LocationInfo locationInfo = AnyPrefUtil.getLocationInfo();
                if (locationInfo != null) {
                    DataConverter.pickMap(mContext, new LatLng(Double.valueOf(locationInfo.latitude), Double.valueOf(locationInfo.longitude)), latLng, position);
                }
            }
        });
        commonBottomListDialog.show(getFragmentManager(), "check_map");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }


    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                // 显示系统小蓝点
                mListener.onLocationChanged(amapLocation);
                MarkerOptions markerOption = new MarkerOptions();
                centerPoint = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                markerOption.position(centerPoint).title("我的位置");
                if (centerMarker!=null){
                    centerMarker.destroy();
                }
                centerMarker = aMap.addMarker(markerOption);
                getMainData(getFrequencyQueryStr());
                //定位成功之后保存一下当前定位数据
                LocationInfo locationInfo = new LocationInfo();
                double longitude = amapLocation.getLongitude();
                double latitude = amapLocation.getLatitude();
                longitude = ArithUtil.round(longitude, 6);
                latitude = ArithUtil.round(latitude, 6);
                locationInfo.longitude = longitude+ "";
                locationInfo.latitude = latitude + "";
                locationInfo.locationTime = System.currentTimeMillis();
                AnyPrefUtil.saveLocationInfo(locationInfo);

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Logger.e(errText);
            }
        }
    }

    /**
     * 此处显示多个定位点
     */
    private void displayMarkers(List<RiskPoint> gkzydyBeans) {
        pointList.clear();
        RiskPoint gkzydyBean = null;
        //先把之前的都去掉
        for (int i = 0; i < markers.size(); i++) {
            markers.get(i).remove();
        }
        markers.clear();

        for (int i = 0; i < gkzydyBeans.size(); i++) {
            gkzydyBean = gkzydyBeans.get(i);
            MarkerOptions markerOption = new MarkerOptions();
            String position = gkzydyBean.getGps();
            if (!TextUtils.isEmpty(position) && position.contains(";")) {
                LatLng latLng = DataConverter.fromStrToLatLng(position);
                pointList.add(latLng);
//                markerOption.position(latLng)
//                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title(gkzydyBean.getName());
//                Marker marker = aMap.addMarker(markerOption);
//                marker.showInfoWindow();
//                markers.add(marker);
                markers.add(getMarker(latLng, gkzydyBean.getName()));
            }
        }
        zoomToSpanWithCenter();
//        zoomToSpan();
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            location();
        }
    }

    private void location() {
        mlocationClient = new AMapLocationClient(getContext());
        //设置定位监听
        mlocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        //设置单次定位
        mLocationOption.setOnceLocation(false);
        mLocationOption.setInterval(1000 * 60 * 10);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        mLocationOption.setNeedAddress(true);
        mlocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
//        mListener = null;
//        if (mlocationClient != null) {
//            mlocationClient.stopLocation();
//            mlocationClient.onDestroy();
//        }
//        mlocationClient = null;
    }


    //////////////////////////一下为坐标marker的显示///////////////////////////////////////
    private Marker getMarker(LatLng position, String title) {
        if (position != null) {
            //初始化marker内容
            MarkerOptions markerOptions = new MarkerOptions();
            //这里很简单就加了一个TextView，根据需求可以加载复杂的View
            View view = View.inflate(mContext, R.layout.layout_custom_marker_view, null);
            TextView textView = ((TextView) view.findViewById(R.id.title));
            textView.setText(title);
            BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(view);
            markerOptions.position(position).icon(markerIcon);
            return aMap.addMarker(markerOptions);
        } else {
            return null;
        }
    }

    /**
     * 缩放移动地图，保证所有自定义marker在可视范围中，且地图中心点不变。
     */
    public void zoomToSpanWithCenter() {
        if (pointList != null && pointList.size() > 0) {
            if (aMap == null) {
                return;
            }
//            centerMarker.setVisible(true);
//            centerMarker.showInfoWindow();
            LatLngBounds bounds = getLatLngBounds(centerPoint, pointList);
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
        }
    }

    //根据中心点和自定义内容获取缩放bounds
    private LatLngBounds getLatLngBounds(LatLng centerpoint, List<LatLng> pointList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (centerpoint != null) {
            for (int i = 0; i < pointList.size(); i++) {
                LatLng p = pointList.get(i);
                LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
                b.include(p);
                b.include(p1);
            }
        }
        return b.build();
    }

    /**
     * 缩放移动地图，保证所有自定义marker在可视范围中。
     */
    public void zoomToSpan() {
        if (pointList != null && pointList.size() > 0) {
            if (aMap == null) {
                return;
            }
            centerMarker.setVisible(true);
            LatLngBounds bounds = getLatLngBounds(pointList);
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
        }
    }

    /**
     * 根据自定义内容获取缩放bounds
     */
    private LatLngBounds getLatLngBounds(List<LatLng> pointList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        for (int i = 0; i < pointList.size(); i++) {
            LatLng p = pointList.get(i);
            b.include(p);
        }
        return b.build();
    }

    @Subscribe
    public void onEventRefreshPage(EventRefreshPage iEvent) {
        if (iEvent != null) {
            if (iEvent.type == Config.EventKit.KEY_EVENT_REFRESH_SET_POSITION) {
                refreshPage();
            }
        }
    }

    /**
     * 刷新页面
     */
    public void refreshPage() {
        location();
    }
}
